from hashlib import md5
from annoying.decorators import render_to
from django.shortcuts import redirect

from core.forms import RegisterForm
from core.models import InternalCredential
from core.views import index
from core.lib import auth


@render_to('register.html')
def register(request):
    if request.method == 'POST':
        form = RegisterForm(request.POST)
        if form.is_valid():
            login = form.cleaned_data['login']
            password = form.cleaned_data['password']
            internal_credential = InternalCredential(login=login,
                password_hash=md5(password).hexdigest())
            try:
                ip = request.META['REMOTE_ADDR']
                user = auth.register(internal_credential, ip)
            except InternalCredential.AlreadyExists:
                form.errors['login'] = ['Specified login already exists.']
                return {'form': form}

            request.session['user_id'] = user.id

            return redirect(index)
    else:
        form = RegisterForm()

    return {'form': form}